﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;



namespace OnlineMealOrdering.Extends.Attributes
{
    public class APIAuthorizeAttribute:AuthorizeAttribute
    {
        public new string[] Roles { get; set; }

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            HttpResponseMessage unAuthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);

            if (Roles == null || Roles.Count() == 0)
            {
                actionContext.Response = unAuthorizedResponse;
                return;
            }
            
            //get usercode and password
            string userCode = string.Empty;
            string userPassword = string.Empty;
            if (actionContext.Request.Headers.Contains("mvc_web_api_user_code"))
                userCode = actionContext.Request.Headers.GetValues("mvc_web_api_user_code").First();
            if (actionContext.Request.Headers.Contains("mvc_web_api_user_password"))
                userPassword = actionContext.Request.Headers.GetValues("mvc_web_api_user_password").First();

            //validate account
            bool loginResult = Membership.ValidateUser(userCode, userPassword);
            if (!loginResult)
            {
                actionContext.Response = unAuthorizedResponse;
                return;
            }
            
            //get roles
            var userRoles = System.Web.Security.Roles.GetRolesForUser(userCode);
            if (userRoles == null || userRoles.Count() == 0)
            {
                actionContext.Response = unAuthorizedResponse;
                return;
            }

            //check authorization

            if (CheckRoleInUserRoles(Roles,userRoles))
            {
                //pass authorize 
                return;
            }
            else
            {
                //如果让actionContext.Response =unAuthorizedResponse会在客户端反复发送request到服务器，原因不明
                actionContext.Response = new HttpResponseMessage();
                return;
            }
        }

        bool CheckRoleInUserRoles(string[] requiredRoles,string[] userRoles)
        {
            bool result = false;

            foreach (string userRole in userRoles)
            {
                if (requiredRoles.Contains(userRole))
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}